/**
 * 状态管理器
 * @param Vuex
 * @returns {Store<{products: *[]}> | Store}
 */

export default function(Vuex) {
  return new Vuex.Store({
    state: {
      products: [
        {name: '鼠标', price: 20},
        {name: '键盘', price: 40},
        {name: '耳机', price: 60},
        {name: '显示屏', price: 80}
      ],
      count: 10
    },
    getters: {
      saleProducts: (state) => {
        let saleProducts = state.products.map(product => {
          return {
            name: product.name,
            price: product.price / 2
          }
        })
        return saleProducts
      }
    },
    mutations: {
      minusPrice (state, payload) {
        state.products.forEach(product => {
          product.price -= payload
        })
      },
      minusCount (state, num) {
        state.count -= num
      }
    },
    actions: {
      // 添加actions
      minusPriceAsync: function (context, payload) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            context.commit('minusPrice', payload) // context提交
            resolve(context)
          }, 2000)
        })
      },
    }
  })
}
